<?php
/**
 * Created by PhpStorm.
 * User: renyi
 * Date: 2017/1/3
 * Time: 上午9:52
 */

namespace App\Helper;

use Illuminate\Support\Facades\Log;
use zgldh\QiniuStorage\QiniuStorage;

class QiniuHelper
{
    /**
     * 转换七牛图片地址
     * @param $files: array，而每个item需要是 ['key' => '', ...]
     * @return array
     */

    public static function setFullUrl($files)
    {
        if (empty($files))
        {
            return [];
        }

        $disk = QiniuStorage::disk('qiniu');
        foreach ($files as &$work)
        {
            if (!isset($work['key']))
            {
                continue;
            }  //避免前端出错，但是这不应该出现，出现则是之前的保存有问题
            if (strpos($work['key'], 'http') === 0)
            {
                $url = $work['key'];
                //                $previewUrl = $work['key'] . '?imageMogr2/gravity/Center/crop/200x200';
                // 上传后，用来预览的地址，直接瘦身即可，没有必要做各种裁剪在展示；
                // $previewUrl = $work['key'] . "?imageMogr2/gravity/Center/crop/500x500";
                $previewUrl = ImageHelper::addImageParameter($url, "imageMogr2/gravity/Center/crop/500x500");
            }
            else
            {
                $url = $disk->privateDownloadUrl($work['key']);
                //加上图片处理参数以后，一起进去做签字才会有效，直接拼接上面的签字与图片处理参数是无效的
                //也不能像范例一样调$disk->imagePreviewUrl()方法取得地址
                // $previewUrl = $disk->privateDownloadUrl($work['key'] . '?imageView2/1/w/200/h/200/interlace/1');

                #图片截取
                // $previewUrl = $disk->privateDownloadUrl($work['key'] . '?imageView2/1/w/200/h/200/interlace/1');
                $previewUrl = ImageHelper::addImageParameter($url, "imageView2/1/w/200/h/200/interlace/1");
            }


            if (!empty($url))
            {
                $work['url'] = $url;
            }

            if (!empty($previewUrl))
            {
                $work['preview'] = $previewUrl;
            }

            // 仅供前端展示时，标识使用；在点击叉号删除图片时，找到此图片另外渲染的元素位置；
            $work['image_id'] = md5($work['url']);
        }

        return $files;
    }

    public static function setImageFullUrl($file)
    {
        if (empty($file))
        {
            return [];
        }

        $disk = QiniuStorage::disk('qiniu');
        if (strpos($file, 'http') === 0)
        {
            $url = $file;
            $previewUrl = ImageHelper::addImageParameter($url, "imageView2/1/w/300/h/300");
        }
        else
        {
            $url = $disk->privateDownloadUrl($file);
            if ($length = strpos($url, '?'))
            {
                $url = substr($url, 0, $length);
            }

            #图片截取
            $previewUrl = ImageHelper::addImageParameter($url, "imageView2/1/w/300/h/300");
        }

        $image['url'] = $file;
        if (!empty($url))
        {
            $image['url'] = $url;
        }

        if (!empty($previewUrl))
        {
            $image['preview'] = $previewUrl;
        }

        return $image;
    }

    /**
     * 转换七牛图片地址
     * @param $files: array，而每个item需要是 ['key' => '', ...]
     * @return array
     */

    public static function setTeamInquiryFullUrl($files)
    {
        if (empty($files))
        {
            return [];
        }

        $disk = QiniuStorage::disk('qiniu');
        foreach ($files as &$work)
        {
            if (!isset($work['key']))
            {
                continue;
            }  //避免前端出错，但是这不应该出现，出现则是之前的保存有问题

            $url = $work['key'];
            //加上图片处理参数以后，一起进去做签字才会有效，直接拼接上面的签字与图片处理参数是无效的
            //也不能像范例一样调$disk->imagePreviewUrl()方法取得地址
            #此方法是图片截取，在图片中间截取一小块，不符合需求
            #$previewUrl = $disk->privateDownloadUrl($work['key'] . '?imageMogr2/gravity/Center/crop/200x200');

            #图片截取
            // $previewUrl = $work['key'] . '?imageView2/1/w/200/h/200/interlace/1';
            $previewUrl = ImageHelper::addImageParameter($url, "imageView2/1/w/200/h/200/interlace/1");

            if (!empty($url))
            {
                $work['url'] = $url;
            }

            if (!empty($previewUrl))
            {
                $work['preview'] = $previewUrl;
            }
        }

        return $files;
    }

    public static function transferImagesFromWechat($images)
    {
        if (empty($images))
        {
            return [];
        }

        $wechat = app('wechat.official_account');
        $material = $wechat->media;

        //取得图片数据并保存到七牛
        $disk = QiniuStorage::disk('qiniu');
        $disk->uploadToken();

        $new = [];
        LogHelper::info('$images::::::::::::' . json_encode($images));
        foreach ($images as $image)
        {
            LogHelper::info('$image::::::::::::' . $image['server_id']);
            try
            {
                $upImage = $material->get($image['server_id']);
            }
            catch (\Exception $e)
            {
                $upImage = '';
            }

            if (!empty($upImage))
            {
                $fname = "inquiry-{$image['type']}-" . time() . rand(999, 9999) . ".png";
                $rc    = $disk->put($fname, $upImage);
                LogHelper::info('$upImage::::::::::::' . $upImage);
                LogHelper::info('$fname::::::::::::' . $fname);
                LogHelper::info('$rc::::::::::::' . $rc);
                if ($rc)
                {
                    $url = $disk->privateDownloadUrl($fname);
                    if ($length = strpos($url, '?'))
                    {
                        $url = substr($url, 0, $length);
                    }
                    $new[] = [
                        'type' => $image['type'],
                        'key'  => $url
                    ];
                }
                else
                {
                    Log::error($image['server_id'] . ' upload to qiniu failed. type: ' . $image['type']);
                }
            }

        }

        return $new;
    }

    public static function uploadImagesFromWechat($images)
    {
        if (empty($images))
        {
            return [];
        }

        $wechat   = app('wechat.official_account');
        $material = $wechat->media;

        //取得图片数据并保存到七牛
        $disk = QiniuStorage::disk('qiniu');
        $disk->uploadToken();

        $new = [];
        LogHelper::info('$images :::::::::::: ' . json_encode($images));
        foreach ($images as $image)
        {
            LogHelper::info('$image server_id :::::::::::: ' . $image['server_id']);
            try
            {
                $upImage = $material->get($image['server_id']);
            }
            catch (\Exception $e)
            {
                $upImage = '';
            }

            if (!empty($upImage))
            {
                $fname = "diabetes-{$image['type']}-" . time() . rand(999, 9999) . ".png";
                $rc    = $disk->put($fname, $upImage);

                LogHelper::info('$upImage :::::::::::: ' . json_encode($upImage));
                LogHelper::info('$fname   :::::::::::: ' . $fname);
                LogHelper::info('$rc      :::::::::::: ' . $rc);

                if ($rc)
                {
                    $new[] = [
                        'type' => $image['type'],
                        'key'  => $fname
                    ];
                }
                else
                {
                    Log::error($image['server_id'] . ' upload to qiniu failed. type: ' . $image['type']);
                }
            }
        }

        return $new;
    }

    /**
     * 上传医生照片
     * @param $file
     * @return string
     */
    public static function uploadImageForDoctor($file)
    {
        // 判断是否有文件上传

        if ($file)
        {
            // 初始化
            $disk = QiniuStorage::disk('qiniu');
            // 重命名文件
            $fileName = md5($file->getClientOriginalName() . time() . rand()) . '.' . $file->getClientOriginalExtension();
            // 上传到七牛
            $bool = $disk->put('doctor_' . $fileName, file_get_contents($file->getRealPath()));
            // 判断是否上传成功
            if ($bool)
            {
                return $disk->privateDownloadUrl('doctor_' . $fileName);
            }
            return '上传失败';
        }

        return '没有文件';
    }

}
